package com.qs.eggs.view.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.qs.eggs.Constants;
import com.qs.eggs.R;
import com.qs.eggs.adapter.SubmitGoodsAdapter;
import com.qs.eggs.base.activity.BaseActivity;

import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Response;

public class SubmitOrderActivity extends BaseActivity implements View.OnClickListener{
    private String proid,type,totalCount;
    private TextView name,number,address,price,rmb;
    private RelativeLayout rl;
    private Button ok;
    private String allId;
    private String iscart;
    private String listCount;
    private String id;
    private ArrayList<HashMap<String, Object>> putong = null;
    private RecyclerView recyclerView;
    private SubmitGoodsAdapter orderAdapter;
    private String custid,custname,custphone;
    private String provinceid,cityid,areaid,villageid,custaddress;
    private String jiage,orderMoney,proname,autoname,count1,money,specification,count;
    private  ArrayList<HashMap<String,String>> orderList;
    private String province,city,area,village;

    private String allMoney;
    public static Activity instance;

    @Override
    protected int getContentView() {
        return R.layout.activity_submit_order;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        instance=this;
        iscart=getIntent().getStringExtra("iscart");
        if(iscart.equals("true")){
            proid="";
            type="";
            totalCount=getIntent().getStringExtra("totalcount");
            allId=getIntent().getStringExtra("ids");
            listCount=getIntent().getStringExtra("listcount");
            getCartInfo();
        }else if (iscart.equals("false")){
            proid=getIntent().getStringExtra("proid");
            type=getIntent().getStringExtra("type");
            totalCount=getIntent().getStringExtra("totalcount");
            id=getIntent().getStringExtra("id");
            getProduct();
        }
        initView();
        getInfo();
        searchAddress();

    }

    private void initView(){
        recyclerView=(RecyclerView)findViewById(R.id.recycler_view);
        name=(TextView)findViewById(R.id.name);
        number=(TextView)findViewById(R.id.number);
        address=(TextView)findViewById(R.id.address);
        price=(TextView)findViewById(R.id.price);
        rmb=(TextView)findViewById(R.id.rmb);
        ok=(Button)findViewById(R.id.ok);
        rl=(RelativeLayout) findViewById(R.id.rl);
       // lv=(ListView)findViewById(R.id.lv);
        ok.setOnClickListener(this);
        rl.setOnClickListener(this);

    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ok:
                if (address.getText().equals("")){
                    Toast.makeText(SubmitOrderActivity.this,"地址不能为空",Toast.LENGTH_SHORT).show();
                }else {
                    getOrder();
                }
                break;
            case R.id.rl:
                Intent intent=new Intent(SubmitOrderActivity.this,AddressManagement1Activity.class);
                startActivityForResult(intent,99);
                break;
        }
    }
    //获得个人信息
    private void getInfo(){
        OkGo.post(Constants.URL_BASE+"personal?action=getPersonalInfo")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        System.out.print("个人信息=="+s);
                        try {
                            JSONArray jsonArray = new JSONArray(s);
                            for (int i = 0; i < jsonArray.length(); i++) {
                                custname=jsonArray.getJSONObject(i).getString("name");
                                custphone=jsonArray.getJSONObject(i).getString("phone");
                                custid=jsonArray.getJSONObject(i).getString("id");
                                name.setText("收货人:"+custname+"");
                                number.setText(custphone);
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
    //查询默认地址
    private void searchAddress(){
        HashMap<String,String> map=new HashMap<String, String>();
        map.put("id","");
        Gson gson=new Gson();
        String str=gson.toJson(map);
        OkGo.post(Constants.URL_BASE+"myorder?action=searchAddressM")
                .params("data",str)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        System.out.print("默认地址=="+s);
                        if (s.equals("\"false\"")) {
                            address.setText("");
                            new AlertDialog.Builder(SubmitOrderActivity.this)
                                    .setTitle("")
                                    .setMessage("默认地址为空，请先添加默认地址")
                                    .setPositiveButton("确定",
                                            new DialogInterface.OnClickListener() {

                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    Intent intent=new Intent(SubmitOrderActivity.this,AddressManagement1Activity.class);
                                                    startActivity(intent);
                                                    dialog.dismiss();
                                                }
                                            }).show();
                        }else {
                            try {
                                JSONArray jsonArray = new JSONArray(s);
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                                    provinceid = jsonObject.getString("provinceid");
                                    cityid = jsonObject.getString("cityid");
                                    areaid = jsonObject.getString("areaid");
                                    villageid = jsonObject.getString("villageid");
                                    custaddress = jsonObject.getString("address");

                                    province = jsonObject.getString("province");
                                    city = jsonObject.getString("city");
                                    area = jsonObject.getString("area");
                                    village = jsonObject.getString("village");
                                    address.setText("收货地址:"+ custaddress + "");
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }


    //获取购物车选中的商品的信息
    private void getCartInfo(){
        HashMap<String,String> map=new HashMap<String, String>();
        map.put("proid","");
        map.put("type","");
        map.put("shoppingcardids",allId);
        Gson gson=new Gson();
        String str=gson.toJson(map);

        OkGo.post(Constants.URL_BASE+"myorder?action=searchProDetai")
                .params("data",str)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        System.out.print("商品信息=="+s);
                        try {
                            putong=new ArrayList<>();
                            JSONArray jsonArray = new JSONArray(s);
                            //addOrderList中的数据
                            orderList=new ArrayList<HashMap<String, String>>();
                            listCount=listCount.substring(1);
                            String[] temp=listCount.split(",");
                            ArrayList<String> single =new ArrayList<String>();
                            for(int i=0;i<temp.length;i++){
                                single.add(temp[i]);
                            }
                            for (int i=0;i<jsonArray.length();i++){
                                JSONObject jsonObject=jsonArray.getJSONObject(i);
                                HashMap<String,Object> map=new HashMap<>();
                                proid=jsonObject.getString("proid");
                                proname=jsonObject.getString("proname");
                                autoname=jsonObject.getString("autoname");
                                money=jsonObject.getString("money");
                                jiage=jsonObject.getString("price");
                                type=jsonObject.getString("type");
                                specification=jsonObject.getString("specification");
                                count=jsonObject.getString("count");

                                map.put("proid",proid);
                                map.put("proname",proname);
                                map.put("autoname",autoname);
                                map.put("count",single.get(i));
                                map.put("money",money);
                                map.put("price",jiage);
                                map.put("type",type);
                                map.put("specification",specification);
                                //map.put("count",totalCount);
                                putong.add(map);

                                //提交订单的商品数据
                                HashMap<String,String> orderListMap=new HashMap<>();
                                orderListMap.put("proid",proid);
                                orderListMap.put("proname",proname);
                                orderListMap.put("specification",specification);
                                orderListMap.put("price",jiage);
                                orderListMap.put("type",type);
                                orderListMap.put("count",single.get(i));
                                orderListMap.put("money",String.valueOf(Double.valueOf(jiage)*Integer.parseInt(single.get(i))));
//                                orderListMap.put("count",totalCount);
//                                orderListMap.put("money",(Double.valueOf(jiage)*Integer.parseInt(totalCount)+""));
                                orderListMap.put("table","pro_order_detail");
                                orderList.add(orderListMap);

                            }


                            orderAdapter=new SubmitGoodsAdapter(SubmitOrderActivity.this,putong,listCount);
                            recyclerView.setLayoutManager(new LinearLayoutManager(SubmitOrderActivity.this));
                            recyclerView.setAdapter(orderAdapter);

                            orderMoney=Double.valueOf(jiage)*Integer.parseInt(totalCount)+"";
                            price.setText("¥"+orderAdapter.getTotalPrice());
                            //rmb.setText("¥"+orderAdapter.getTotalPrice());
                            allMoney=price.getText().toString().substring(1);
                            rmb.setText(price.getText().toString());


                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


    //得到正常商品详情
    private void getProduct(){
        HashMap<String,String> map=new HashMap<String, String>();
        map.put("proid",proid);
        map.put("id",id);
        map.put("type",type);
        map.put("count",totalCount);
        map.put("shoppingcardids","");
        Gson gson=new Gson();
        String str=gson.toJson(map);

        OkGo.post(Constants.URL_BASE+"myorder?action=searchProDetai")
                .params("data",str)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        System.out.print("正常商品详情=="+s);
                        try {
                            putong=new ArrayList<>();
                            JSONArray jsonArray = new JSONArray(s);
                            for (int i=0;i<jsonArray.length();i++){
                                JSONObject jsonObject=jsonArray.getJSONObject(i);
                                HashMap<String,Object> map=new HashMap<>();
                                //proid=jsonObject.getString("proid");
                                proname=jsonObject.getString("proname");
                                autoname=jsonObject.getString("autoname");
                                count1=jsonObject.getString("count");
                                //money=jsonObject.getString("money");
                                jiage=jsonObject.getString("price");
                                //type=jsonObject.getString("type");
                                //specification=jsonObject.getString("specification");

                               // map.put("proid",proid);
                                map.put("proname",proname);
                                map.put("autoname",autoname);
                                //map.put("count",count1);
                               // map.put("money",money);
                                map.put("price",jiage);
                                //map.put("type",type);
                                //map.put("specification",specification);
                                map.put("count",totalCount);
                                putong.add(map);
                                orderMoney=Double.valueOf(jiage)*Integer.parseInt(totalCount)+"";
                                price.setText("¥"+orderMoney+"");
                                rmb.setText("¥"+orderMoney+"");
                                allMoney=price.getText().toString().substring(1);
                            }

                            orderAdapter=new SubmitGoodsAdapter(SubmitOrderActivity.this,putong,totalCount+",");
                            recyclerView.setLayoutManager(new LinearLayoutManager(SubmitOrderActivity.this));
                            recyclerView.setAdapter(orderAdapter);
                            //addOrderList中的数据
                            orderList=new ArrayList<HashMap<String, String>>();
                            HashMap<String,String> orderListMap=new HashMap<>();
                            orderListMap.put("proid",proid);
                            orderListMap.put("proname",proname);
                            orderListMap.put("specification",specification);
                            orderListMap.put("price",jiage);
                            orderListMap.put("type",type);
                            orderListMap.put("count",totalCount);
                            orderListMap.put("money",(Double.valueOf(jiage)*Integer.parseInt(totalCount)+""));
                            orderListMap.put("table","pro_order_detail");
                            orderList.add(orderListMap);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }
    //生成订单
    private void getOrder(){
        //data中的数据
        HashMap<String,Object> dataMap=new HashMap<>();
        dataMap.put("custid",custid);
        dataMap.put("custname",custname);
        dataMap.put("custphone",custphone);
        dataMap.put("custaddress",address.getText().toString().substring(5));
        dataMap.put("totalcount",totalCount);
        dataMap.put("totalmoney",allMoney);
        dataMap.put("provinceid",provinceid);
        dataMap.put("cityid",cityid);
        dataMap.put("areaid",areaid);
        dataMap.put("villageid",villageid);
        dataMap.put("table","pro_order");

        dataMap.put("proList",orderList);
        Gson gson=new Gson();
        String Data=gson.toJson(dataMap);

        OkGo.post(Constants.URL_BASE+"myorder?action=addMyOrder")
                .params("data",Data)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        System.out.print("订单生成成功=="+s);
                        String temp=s.substring(9);
                        String orderno=temp.substring(0,14);
                        if (s.equals("\"false\"")){
                            Toast.makeText(SubmitOrderActivity.this,"提交订单失败",Toast.LENGTH_SHORT).show();
                        }else{
                            Intent intent=new Intent(SubmitOrderActivity.this,PayMethodActivity.class);
                            intent.putExtra("orderno",orderno);
                            intent.putExtra("ordermoney",price.getText().toString().substring(1));
                            intent.putExtra("biaoshi","1");
                            startActivity(intent);
                        }
                    }
                });
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            switch (resultCode) {
                case 99:
                    address.setText("收货地址:"+data.getStringExtra("address")+"");
                    provinceid=data.getStringExtra("provinceid");
                    cityid=data.getStringExtra("cityid");
                    areaid=data.getStringExtra("areaid");
                    villageid=data.getStringExtra("villageid");
                    break;
                default:
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }


}
